//
//  WmcTeamAlbumBrowser.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/10/25.
//

import Foundation
import RxSwift

/// 照片资源图片模型遵循协议
protocol WmcPhotoModelProtocol {
    var id: Int { get set }
}

/// 相册视频预览
class WmcTeamAlbumBrowser: NSObject {
    private let bag = DisposeBag()
    /// 当前相册
    private let album: WmcMediaTeamAlbumModel
    /// 浏览数据源
    private var browserDataSource: [WmcMedia]
    /// 原始数据源
    private var originalDataSource: [WmcPhotoModelProtocol]

    /// 构造器
    /// - Parameters:
    ///   - album: 当前相册
    ///   - browserDataSource: 浏览数据源
    ///   - originalDataSource: 原始数据源
    init(album: WmcMediaTeamAlbumModel,
         browserDataSource: [WmcMedia],
         originalDataSource: [WmcPhotoModelProtocol])
    {
        self.album = album
        self.browserDataSource = browserDataSource
        self.originalDataSource = originalDataSource
    }

    /// 浏览照片
    func browserPhotos(model: WmcPhotoModelProtocol, title: String? = nil) {
        let browseVM = WmcMediaBrowseVM()
        browseVM.topLeftStyle = .backTitle(title: title ?? album.name)
        browseVM.albumType = .cloud
        browseVM.showIndex = getIndexForCurrentMediaItem(model: model)
        browseVM.mediaList = browserDataSource
        browseVM.backStyle = .right // 从右侧返回出
        browseVM.shareFriendsCircleMode = .custom
        browseVM.shareWechatMode = .custom

        browseVM.actionBlock = { type, index, vm in
            switch type {
            case .delete:
                vm.presentDeleteAlert {
                    WmcHudManager.loading()
                    self.deleteImage(index: index) {
                        WmcHudManager.dismiss()
                        WmcHudManager.toast("删除成功")
                        NotificationCenter.default.post(name: NSNotification.Name("com.watermark.cloudAlbumDataDidChange"), object: self, userInfo: nil)
                        NotificationCenter.default.post(name: NSNotification.Name("com.watermark.classifyAlbumDataDidChange"), object: self, userInfo: nil)
                        browseVM.remove(at: index)
                    } failure: { _ in
                        WmcHudManager.dismiss()
                        WmcHudManager.toast("非本人照片，无法删除")
                    }
                }
            case .save:
                let wmcMedia = self.browserDataSource[index]
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    wmcImage.loadUIImage { image in
                        let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
                        if photoAlbumStatus.info.isAvailable {
                            UIImageWriteToSavedPhotosAlbum(image,
                                                           self,
                                                           #selector(self.saveImage(_:didFinishSaving:contextInfo:)),
                                                           nil)
                        } else {
                            WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
                        }
                    }
                } else if let wmcVideo = wmcMedia as? WmcVideo { // 视频
                    switch wmcVideo.videoType {
                    case let .url(url):
                        let urlString = URL.YP.Create(url).yp.string
                        guard let keyWindow = UIApplication.shared.keyWindow else { return }
                        let progressBarView = WmcProgressBarView.showInView(keyWindow)

                        progressBarView.cancelClosure = {
                            WmcDownloadManager.shared.cancel()
                        }

                        WmcDownloadManager.shared.downloadFile(url: urlString) { value in
                            let progressText = String(format: "正在下载中%.2f", value * 100) + "%"
                            progressBarView.setProgress(Float(value), progressText: progressText)
                        } success: {
                            progressBarView.dismiss()
                            WmcHudManager.toast("已保存到系统相册")
                        } failure: {
                            progressBarView.dismiss()
                            WmcHudManager.toast("保存失败")
                        }

                    default: break
                    }
                }
            case .shareWechat:
                let wmcMedia = self.browserDataSource[index]
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    self.shared(image: wmcImage, scene: .session)
                } else if wmcMedia is WmcVideo { // 视频
                    self.shareVideo(index: index, type: .session)
                }
            case .shareFriendsCircle:
                let wmcMedia = self.browserDataSource[index]
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    self.shared(image: wmcImage, scene: .friendCircle)
                } else if wmcMedia is WmcVideo { // 视频
                    self.shareVideo(index: index, type: .friendCircle)
                }
            default: break
            }
        }
        let vc = WmcNavigatorManager.push(.imageBrowse, style: .alpha, parms: browseVM)
        vc?.hidesBottomBarWhenPushed = true
    }
}

extension WmcTeamAlbumBrowser {
    /// 分享图片
    /// - Parameters:
    ///   - image: 图片
    ///   - scene: 分享类型
    private func shared(image: WmcImage?, scene: WmcShareManager.Scene) {
        guard let wmcImage = image else { return }
        wmcImage.loadUIImage { image in
            WmcShareManager.shareImage(image, scene: scene)
        }
    }

    @objc private func saveImage(_: UIImage, didFinishSaving error: Error?, contextInfo _: AnyObject) {
        if error != nil {
            WmcHudManager.toast("保存失败")
        } else {
            WmcHudManager.toast("已保存到系统相册")
        }
    }

    /// 分享视频链接
    /// - Parameters:
    ///   - index: 第几个
    ///   - type: 分享类型
    /// - Returns: description
    private func shareVideo(index: Int, type: WmcShareManager.Scene) {
        WmcHudManager.loading()
        fetchVideoShare(index: index) { r in
            WmcHudManager.dismiss()
            let icon = UIImage.YP.AppIcon
            WmcShareManager.shareLink(r.url, title: r.title, description: r.content, thumbImage: icon, scene: type)
        } failure: { error in
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
        }
    }
}

extension WmcTeamAlbumBrowser {
    /// 获取当前图片对应索引
    /// - Returns: description
    func getIndexForCurrentMediaItem(model: WmcPhotoModelProtocol) -> Int {
        let index = originalDataSource.firstIndex(where: { $0.id == model.id }) ?? 0
        return index
    }
}

extension WmcTeamAlbumBrowser {
    /// 删除
    /// - Parameters:
    ///   - index: 第几张
    ///   - success: success description
    ///   - failure: failure description
    func deleteImage(index: Int, success: @escaping () -> Void, failure: @escaping (Error?) -> Void) {
        if index < originalDataSource.count {
            let model = originalDataSource[index]
            let busId = album.busId
            WmcMediaTeamManagerAPI.deleteTeamResource(resourceId: model.id, teamId: Int(busId) ?? 0).subscribe(onNext: { [weak self] _ in
                guard let weakSelf = self else { return }
                weakSelf.originalDataSource.remove(at: index)
                weakSelf.browserDataSource.remove(at: index)
                WmcNotificationManager.shared.post(type: .deletePhotoSucceed, object: nil)
                success()
            }, onError: { error in
                failure(error)
            }).disposed(by: bag)
        } else {
            failure(nil)
        }
    }

    /// 获取视频链接
    /// - Parameters:
    ///   - index: 第几条视频
    ///   - success: success description
    ///   - failure: failure description
    func fetchVideoShare(index: Int, success: @escaping (WmcMediaShareModel) -> Void, failure: @escaping (Error?) -> Void) {
        if index < originalDataSource.count {
            let model = originalDataSource[index]
            let busId = album.busId
            WmcMediaTeamAlbumAPI.fetchVideoShareInfo(busId: Int(busId) ?? 0, id: model.id).subscribe(onNext: { r in
                success(r)
            }, onError: { error in
                failure(error)
            }).disposed(by: bag)
        } else {
            failure(nil)
        }
    }
}
